﻿using KZ.Express.H.ENT;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using KZ.Utilities;

namespace KZ.Express.H.CustomControl
{
    public class KZDecimalTextBox : TextBox
    {
        string accepted = "1234567890.\b' '";

        public KZDecimalTextBox()
            : base()
        {
            this.TextAlign = HorizontalAlignment.Right;
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (!accepted.Contains(e.KeyChar) || (e.KeyChar == '.' && this.Text.Contains('.')))
                e.Handled = true;

            int index = this.SelectionStart;
            int pointIndex = this.Text.IndexOf('.');

            string[] text = this.Text.Replace(",", String.Empty).Split('.');
            if (accepted.Contains(e.KeyChar) && e.KeyChar != '\b' && index > pointIndex &&
                text.Length > 1 && text[1].Length >= Utility._INFO.NumberFormat.NumberDecimalDigits)
                e.Handled = true;
        }

        protected override void OnKeyUp(KeyEventArgs e)
        {
            int padright = this.Text.Length - this.SelectionStart;
            string[] text = this.Text.Replace(",", String.Empty).Split('.');

            int j = 1;
            for (int i = text[0].Length - 1; i > 0; i--)
            {
                if (j % 3 == 0)
                    text[0] = text[0].Insert(i, ",");
                j++;
            }

            this.Text = text[0] + (text.Length > 1 ? "." + text[1] : String.Empty);
            this.SelectionStart = this.Text.Length - padright;
            base.OnKeyUp(e);
        }
    }
}
